package com.good.cm;

import com.alibaba.fastjson.JSON;
import com.good.cm.exception.NoLoginException;
import com.good.cm.exception.ParamsException;
import com.good.cm.model.ResultInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
        /*
        全局异常处理两种情况：1.视图 2.接口json 方法标注了@ResponseBody
         */
        //1.判断是否登录
        if (e instanceof NoLoginException){
            ModelAndView mv=new ModelAndView();
            mv.setViewName("nologin");
            mv.addObject("msg","未登录");
            return mv;
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            ResponseBody responseBody=  hm.getMethod().getDeclaredAnnotation(ResponseBody.class);
            if (null==responseBody)
            {
                //视图
                ModelAndView mv=new ModelAndView();
                mv.setViewName("error");
                mv.addObject("msg","系统异常");
                return mv;
            }else{
                //json
                ResultInfo resultInfo=new ResultInfo();
                resultInfo.setCode(300);
                resultInfo.setMsg(e.getMessage());
                httpServletResponse.setContentType("application/json;charset=utf-8");
                httpServletResponse.setCharacterEncoding("utf-8");
                PrintWriter printWriter= null;
                try {
                    printWriter=httpServletResponse.getWriter();
                    printWriter.write(JSON.toJSONString(resultInfo));
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                } finally {
                    if (null!=printWriter)
                    {
                        printWriter.close();
                    }
                }
            }
        }
        return null;
    }
}
